package com.ruoyi.web.controller.campus;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.campus.domain.Department;
import com.ruoyi.campus.service.IDepartmentService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 * 部门信息Controller
 * 
 * @author ruoyi
 * @date 2025-01-08
 */
@Api(tags = "部门信息管理")
@RestController
@RequestMapping("/campus/department")
public class DepartmentController extends BaseController
{
    @Autowired
    private IDepartmentService departmentService;

    /**
     * 查询部门信息列表
     */
    @ApiOperation("查询部门信息列表")
    @RequiresPermissions("campus:department:list")
    @GetMapping("/list")
    public TableDataInfo list(Department department)
    {
        startPage();
        List<Department> list = departmentService.selectDepartmentList(department);
        return getDataTable(list);
    }

    /**
     * 查询部门树形结构列表
     */
    @ApiOperation("查询部门树形结构列表")
    @RequiresPermissions("campus:department:list")
    @GetMapping("/tree")
    public AjaxResult tree(Department department)
    {
        try
        {
            // 参数校验和默认值设置
            if (department == null)
            {
                department = new Department();
            }
            
            // 查询部门列表
            List<Department> departments = departmentService.selectDepartmentList(department);
            
            // 如果没有数据，直接返回空列表
            if (departments == null || departments.isEmpty())
            {
                return AjaxResult.success(new ArrayList<>());
            }
            
            // 构建树形结构
            List<Department> treeData = departmentService.buildDeptTree(departments);
            
            return AjaxResult.success(treeData);
        }
        catch (Exception e)
        {
            logger.error("查询部门树形结构失败", e);
            return AjaxResult.error("查询部门树形结构失败：" + e.getMessage());
        }
    }

    /**
     * 导出部门信息列表
     */
    @ApiOperation("导出部门信息列表")
    @RequiresPermissions("campus:department:export")
    @Log(title = "部门信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public AjaxResult export(Department department)
    {
        List<Department> list = departmentService.selectDepartmentList(department);
        ExcelUtil<Department> util = new ExcelUtil<Department>(Department.class);
        return util.exportExcel(list, "部门信息数据");
    }

    /**
     * 获取部门信息详细信息
     */
    @ApiOperation("查询部门信息")
    @RequiresPermissions("campus:department:get")
    @GetMapping("/{deptId}")
    public AjaxResult getById(@PathVariable("deptId") Long deptId)
    {
        return AjaxResult.success(departmentService.selectDepartmentByDeptId(deptId));
    }



    /**
     * 根据父部门ID查询子部门列表
     */
    @ApiOperation("根据父部门ID查询子部门列表")
    @RequiresPermissions("campus:department:list")
    @GetMapping("/children/{parentId}")
    public AjaxResult getChildren(@PathVariable Long parentId)
    {
        Department department = new Department();
        department.setParentId(parentId);
        List<Department> list = departmentService.selectDepartmentList(department);
        return AjaxResult.success(list);
    }

    /**
     * 新增保存部门信息
     */
    @ApiOperation("新增保存部门信息")
    @RequiresPermissions("campus:department:add")
    @Log(title = "部门信息", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult addSave(@RequestBody Department department)
    {
        if (!departmentService.checkDeptNameUnique(department))
        {
            return AjaxResult.error("新增部门'" + department.getDeptName() + "'失败，部门名称已存在");
        }
        if (!departmentService.checkDeptCodeUnique(department))
        {
            return AjaxResult.error("新增部门'" + department.getDeptName() + "'失败，部门编码已存在");
        }
        return toAjax(departmentService.insertDepartment(department, getLoginName()));
    }

    /**
     * 修改保存部门信息
     */
    @ApiOperation("修改保存部门信息")
    @RequiresPermissions("campus:department:edit")
    @Log(title = "部门信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult editSave(@RequestBody Department department)
    {
        if (!departmentService.checkDeptNameUnique(department))
        {
            return AjaxResult.error("修改部门'" + department.getDeptName() + "'失败，部门名称已存在");
        }
        if (!departmentService.checkDeptCodeUnique(department))
        {
            return AjaxResult.error("修改部门'" + department.getDeptName() + "'失败，部门编码已存在");
        }
        else if (department.getParentId() != null && department.getParentId().equals(department.getDeptId()))
        {
            return AjaxResult.error("修改部门'" + department.getDeptName() + "'失败，上级部门不能是自己");
        }
        // 验证父部门是否存在（允许parentId为null或0，表示根节点）
        else if (department.getParentId() != null && !department.getParentId().equals(0L))
        {
            Department parentDepartment = departmentService.selectDepartmentByDeptId(department.getParentId());
            if (parentDepartment == null)
            {
                return AjaxResult.error("修改部门'" + department.getDeptName() + "'失败，上级部门不存在");
            }
        }
        return toAjax(departmentService.updateDepartment(department, getLoginName()));
    }

    /**
     * 删除部门信息
     */
    @ApiOperation("删除部门信息")
    @RequiresPermissions("campus:department:remove")
    @Log(title = "部门信息", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable String ids)
    {
        try
        {
            return toAjax(departmentService.deleteDepartmentByDeptIds(ids));
        }
        catch (Exception e)
        {
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 获取部门点位数量统计
     */
    @ApiOperation("获取部门点位数量统计")
    @RequiresPermissions("campus:department:list")
    @GetMapping("/pointCount/{deptId}")
    public AjaxResult getPointCount(@PathVariable Long deptId)
    {
        try
        {
            int pointCount = departmentService.getPointCountByDeptId(deptId);
            return AjaxResult.success("查询成功", pointCount);
        }
        catch (Exception e)
        {
            return AjaxResult.error("查询失败：" + e.getMessage());
        }
    }


}